<template>
  <a-modal v-model="visible" :afterClose="() => (visible = false)" :closable="modal.closable">
    <template slot="title"
      ><a-icon v-if="modal.icon" :type="modal.icon" class="_mr-10" :style="{ color: modal.iconColor }" />{{
        modal.title
      }}</template
    >
    <template slot="footer">
      <a-button key="back" v-bind="modal.cancelButtonProps" :loading="cancelLoading" @click="handleCancel">
        {{ modal.cancelText }}
      </a-button>
      <a-button key="submit" type="primary" v-bind="modal.cancelButtonProps" :loading="okLoading" @click="handleOk">
        {{ modal.okText }}
      </a-button>
    </template>
    <div>
      {{ modal.content }}
    </div>
  </a-modal>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      okLoading: false,
      cancelLoading: false,
      modal: {
        icon: '',
        title: '',
        content: '',
        okText: '',
        cancelText: '',
        okButtonProps: {},
        cancelButtonProps: {},
        closable: true,
        onCancel: null,
        onOk: null
      }
    }
  },
  methods: {
    open(data) {
      this.visible = true
      this.modal = data
    },
    async handleOk() {
      this.modal.okLoading = true
      try {
        await this.modal.onOk()
        this.visible = false
        this.$emit('ok')
      } catch (error) {
        console.error(error)
      } finally {
        this.modal.okLoading = false
      }
    },
    async handleCancel() {
      this.modal.cancelLoading = true

      try {
        await this.modal.onCancel()
        this.visible = false
        this.$emit('ok')
      } catch (error) {
        console.error(error)
      } finally {
        this.modal.cancelLoading = false
      }
    }
  },
  mounted() {}
}
</script>
